<?php
require_once 'Zend/Db/Table.php';
class St_Acl{
    protected $_permissions = array();
    protected $userData = array();
    public function  __construct($userArray) {
        $this->userData = $userArray;
        $db = St_Registry::getDB ();
        $groupSelect = $db->select()->from(array('gp' => "group_permission"));
        $groupSelect->where("gp.GroupID = '{$userArray['GroupID']}'");
        $select = $db->select ()
                ->from ( array('p' => 'permission' ))
                ->joinLeft(array('s' => $groupSelect), 'p.PermissionID = s.PermissionID', array('GroupID' => 'GroupID'))
                ->order("PermissionID ASC")
                ;
        $permissionList = $db->fetchAll($select);
        foreach($permissionList as $k => $v) {
            if($v['GroupID']) {
                $this->_permissions[$v['PermissionKey']] = $v;
            }
        }
    }

    public function isAllow($key, $redirect = false, $redirectString = false) {
        $isAllow = false;
        $allowAll = true;
        if(is_array($key)) {
            foreach($key as $v) {
                if(!isset($this->_permissions[$v])) {
                    $allowAll = false;
                }
            }
            if($allowAll) {
                $isAllow = true;
            }
        } else {
            if(isset($this->_permissions[$key])) {
                $isAllow = true;
            }
        }
//        print_r($this->userData);die;
        $permissionList = $this->_getPermissionData("group");
        if($permissionList['superadmin_group_id'] == $this->userData['groupID']) {
            $isAllow = true;
        }

        if($redirect && ($isAllow == false)) {
            $redirector = Zend_Controller_Front::getInstance()->getResponse();
            if($redirectString){
                $redirector->setRedirect($redirectString);           
            } else {
                $redirectString = St_Registry::getBaseUrl() . "/access/deny";
                $redirector->setRedirect($redirectString);
            }            
        }

        return $isAllow;
    }

    // list or group
    protected function _getPermissionData($node = "list") {
        $permissionResource = include APPLICATION_PATH . '/configs/permission.php';
        return $permissionResource["permission_" . $node];
    }
    
    public function isMaster() {
        $permissionList = $this->_getPermissionData("group");
        if( $this->userData['GroupID'] == $permissionList['superadmin_group_id']){
            return true;
        }else{
            return false;
        }
    }
}